package com.zuosh.web;

import com.alibaba.fastjson.JSON;
import com.zuosh.common.ResponseHelper;
import com.zuosh.common.RestResponseCode;
import com.zuosh.common.Result;
import com.zuosh.domain.User;
import com.zuosh.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by zuoshuai on 2017/3/17.
 */
@RestController
@RequestMapping(value = "api/user")
public class UserController {
    Logger LOGGER = LoggerFactory.getLogger(this.getClass());//logger
    @Resource
    private UserService userService;

    /**
     * register
     *
     * @param request
     * @param user
     * @return
     */
    @PostMapping(value = "/register")
    public ResponseHelper.RestResponse<Object> registerUser(HttpServletRequest request, @RequestBody User user) {
        if (user == null) {
            return ResponseHelper.buildResponse(RestResponseCode._400, null, "参数不可为空");
        }
        LOGGER.debug("[registerUser]收到注册请求 ,参数: {}", JSON.toJSONString(user));
        Result<Long> register = userService.register(user);
        if (register.isSuccess()) {
            return ResponseHelper.buildResponse(RestResponseCode._200, register.getData(), "ok");
        } else {
            return ResponseHelper.buildResponse(RestResponseCode._500, null, register.getMsg());
        }
    }

    @PostMapping(value = "/login")
    public ResponseHelper.RestResponse<Object> login(HttpServletRequest request, @RequestBody User user) {
        if (user == null) {
            return ResponseHelper.buildResponse(RestResponseCode._400, null, "参数不可为空");
        }
        LOGGER.debug("[login]收到登录请求 ,参数: {}", JSON.toJSONString(user));
        Result<User> register = userService.login(user);
        if (register.isSuccess()) {
            return ResponseHelper.buildResponse(RestResponseCode._200, register.getData(), "ok");
        } else {
            return ResponseHelper.buildResponse(RestResponseCode._500, null, register.getMsg());
        }
    }

    @GetMapping(value = "/activate")
    public ResponseHelper.RestResponse<Object> activateUser(HttpServletRequest request, User user) {
        if (user == null) {
            return ResponseHelper.buildResponse(RestResponseCode._400, null, "参数不可为空");
        }
        LOGGER.debug("[activateUser]收到用户激活请求 ,参数: {}", JSON.toJSONString(user));
        Result<Boolean> activeUserResult = userService.activeUser(user);
        if (activeUserResult.isSuccess()) {
            return ResponseHelper.buildResponse(RestResponseCode._200, activeUserResult.getData(), activeUserResult.getMsg());
        } else {
            return ResponseHelper.buildResponse(RestResponseCode._500, activeUserResult.getData(), activeUserResult.getMsg());
        }
    }
}
